/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 匿名化
 *
 * @author y00464350
 * @since 2022-02-23
 */
@Component
public class LogAnonymizeUtil {
    @Value("${log.anonymize}")
    Boolean isAnonymize = false;

    /**
     * 匿名化字符串
     *
     * @param content 字符串
     * @return 输出
     */
    public String doAnonymize(String content) {
        if (!isAnonymize) {
            return content;
        }
        if (StringUtils.isBlank(content)) {
            return "";
        }
        char[] source = content.toCharArray();
        int segmentSize = 10;
        double bottom = segmentSize * 0.3;
        double top = segmentSize * 0.7;
        for (int i = 0; i < source.length; i = i + segmentSize) {
            if (i + segmentSize <= source.length) {
                fuzzy(source, i + (int) bottom, i + (int) top);
            } else {
                switch (source.length - i) {
                    case 1:
                        source[i] = '*';
                        break;
                    case 2:
                        source[i] = '*';
                        source[i + 1] = '*';
                        break;
                    case 3:
                        source[i] = '*';
                        source[i + 2] = '*';
                        break;
                    case 4:
                    case 5:
                        fuzzy(source, i + 1, i + 3);
                        break;
                    case 6:
                        fuzzy(source, i + 1, i + 4);
                        break;
                    case 7:
                    case 8:
                        fuzzy(source, i + 2, i + 6);
                        break;
                    case 9:
                        fuzzy(source, i + 2, i + 7);
                        break;
                    default:
                        int length = source.length - i;
                        int floor = (int) Math.floor(length * 0.7);
                        int ceil = (int) Math.ceil(length * 0.3);
                        fuzzy(source, i + ceil, i + floor);
                }
            }
        }
        return String.valueOf(source);
    }

    private void fuzzy(char[] source, int startPos, int endPos) {
        for (int i = startPos; i < Math.min(source.length, endPos); i++) {
            source[i] = '*';
        }
    }
}
